package wassalt.client;

import java.util.ArrayList;

import wassalt.Utils.AppConstants;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class FavoriteClientsAdapter extends CursorAdapter{

	/**
	 * A datatype representing a selected contact
	 * @author Aya Kamel
	 */
	public class Selection
	{
		String phone;
		String name;
		
		/**
		 * Constructor
		 * @param n Name of the contact
		 * @param p Phone number
		 */
		public Selection(String n, String p)
		{
			phone = p;
			name = n;
		}
		
		/**
		 * Checks whether the phone corresponds to this instance
		 * @param m
		 * 		The string containing the phone compared
		 * @return
		 * 		true if the strings match false otherwise
		 */
		public boolean is(String m)
		{
			return m.equals(phone);
		}
		
		/**
		 * Gets the name of the contact
		 * @return
		 * 		The string containing the name
		 */
		public String getName()
		{
			return name;
		}
		
		/**
		 * Gets the phone number of the contact
		 * @return
		 * 		The string representing the phone number
		 */
		public String getPhone()
		{
			return phone;
		}

		/**
		 * Checks if the contact phone exists in the concatenated string phone2
		 * @param phone2
		 * 		The concatenated string
		 * @return
		 * 		true if the current phone exists in the concatenated string
		 * 		false otherwise
		 */
		public boolean isIn(String phone2) {
			return phone2.contains(phone);
		}
	}
	
	int type;
	ArrayList<Selection> selected;
	ContentResolver cr;
	
	/**
	 * @author Aya Kamel
	 * @param context
	 * @param c
	 * Constructor -- Creates a new adapter
	 */
	public FavoriteClientsAdapter(Context context, Cursor c, int type) {
		super(context, c);
		this.type = type;
		cr = context.getContentResolver();
		selected = new ArrayList<Selection>();
	}
	
	/**
	 * Checks whether this phone number is in the selected list of phones
	 * @author Aya Kamel
	 * @param phone
	 * 		The number to be checked
	 * @return
	 * 		true if the number is selected
	 * 		false otherwise
	 */
	public boolean isChecked(String phone)
	{
		for(int i=0; i<selected.size(); i++)
		{
			if(selected.get(i).is(phone))
				return true;
			if(selected.get(i).isIn(phone))
				return true;
		}
		return false;
	}
	
	/**
	 * Gets the number of selected items
	 * @author Aya Kamel
	 * @return
	 * 		The number as an integer
	 */
	public int getNumSelected()
	{
		return selected.size();
	}

	/**
	 * @author Aya Kamel
	 * @see android.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor)
	 * Binds the view to the data from the database table
	 */
	@Override
	public void bindView(View view, Context context, Cursor cursor){
		// Fill in the name and phone fields by the contact data
		TextView name = (TextView)view.findViewById(R.id.contact_name);
        TextView phone = (TextView)view.findViewById(R.id.contact_phone);
        CheckBox chk = (CheckBox)view.findViewById(R.id.check);
        
        String phone_num = "";
        String c_name = "";
        
        if(type == AppConstants.FAVORITES) //In the favorites
        {
        	phone_num = cursor.getString(cursor.getColumnIndex(AppConstants.CPHONE));
        	c_name = cursor.getString(cursor.getColumnIndex(AppConstants.CNAME));
        }
        else //In all contacts
        {	
        	c_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor pCur = cr.query(
                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                 null, 
                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                 new String[]{id}, null);
            phone_num = getPhoneNumbers(pCur, c_name);
        	if(phone_num.equals("ERROR"))
        	{
        		phone_num = "";
        		//I HAVE TO DO SOMETHING HERE TO TELL HIM IGNORE THIS ENRTY
        	}
        }
        name.setText(c_name);
        phone.setText(phone_num);
        chk.setChecked(false);
	}

	/**
	 * Gets a string containing all phone numbers in the cursor
	 * @param pCur
	 * 		The input cursor
	 * @return
	 * 		A concatenated string of numbers
	 */
	private String getPhoneNumbers(Cursor pCur, String c_name) {
		String phones = "";
		String indexNumber = ContactsContract.CommonDataKinds.Phone.NUMBER;
		if(pCur != null)
		{
			pCur.moveToFirst();
			try
			{
				int col_index = pCur.getColumnIndexOrThrow(indexNumber);
				phones += pCur.getString(col_index);
				while (pCur.moveToNext()) {
			 		phones += ", " + pCur.getString(col_index);
			 	}
			}
			catch(Exception e)
			{
				Log.i("Tracer", "Problem in "+c_name+":"+e.getMessage());
				return "ERROR";
			}
		}
		return phones;
	}

	/**
	 * @author Aya Kamel
	 * @see android.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
	 * Creates the view which will be used for the list items 
	 */
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		// Set the list to use the contact_item layout for each item in the list
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.contact_item, parent, false);
		bindView(v, context, cursor);
		return v;
	}

	/**
	 * @author Aya Kamel
	 * @see android.widget.CursorAdapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View v = super.getView(position, convertView, parent);
		if(v != null)
		{
			CheckBox chk = (CheckBox)v.findViewById(R.id.check);
			TextView phn = (TextView)v.findViewById(R.id.contact_phone);
			String phone_num = (String) phn.getText();
			chk.setChecked(isChecked(phone_num));
		}
		return v;
	}

	/**
	 * Removes a specific phone number from the selected list
	 * @param phone
	 * 		The phone to be removed
	 * @author Aya Kamel
	 */
	public void remove(String phone) {
		for(int i=0; i<selected.size(); i++)
		{
			if(selected.get(i).is(phone))
			{
				selected.remove(i);
				break;
			}
		}
	}

	/**
	 * If the contact is in the selected list it removes it, adds it otherwise
	 * @param phone_num
	 * 		The phone to be checked/unchecked
	 * @param name
	 * 		The of the contact to be checked/unchecked
	 * @return
	 * 		true if the contact was added false otherwise
	 * @author Aya Kamel
	 */
	public boolean check(String phone_num, String name) {
		if(isChecked(phone_num))
		{
			remove(phone_num);
			return false;
		}
		else
		{
			selected.add(new Selection(name, phone_num));
			return true;
		}
	}
}
